#include "bookdatabase.h"

BookDatabase::BookDatabase()
{
    bookdb = QSqlDatabase::addDatabase("QSQLITE","first");
    bookdb.setDatabaseName("book.db");
    if(!bookdb.open())
    {
        qDebug("book.db open is false");
    }
    else
    {
        qDebug("book.db open is OK");
    }
    //创建一个表格，主键值为id
    QSqlQuery bookquery(bookdb);//使query关联数据库
    bookquery.exec("create table book (id QString primary key, name QString,image QString)");

    //写入数据
    //注意ID号不能重复，否则直接覆盖
    QString sql = "insert into book(id,name,image) values(:id,:name,:image)";
    bookquery.prepare(sql);
    bookquery.bindValue(":id", "A125634897102");
    bookquery.bindValue(":name", "《思想道德修养与法律基础》");
    bookquery.bindValue(":image","./books/A125634897102.png");
    bookquery.exec();

    bookquery.prepare(sql);
    bookquery.bindValue(":id", "B673598223444");
    bookquery.bindValue(":name", "《时事报告大学生版》");
    bookquery.bindValue(":image","./books/B673598223444.png");
    bookquery.exec();

    bookquery.prepare(sql);
    bookquery.bindValue(":id", "C111222555411");
    bookquery.bindValue(":name", "《考研政治黄皮书》");
    bookquery.bindValue(":image","./books/C111222555411.png");
    bookquery.exec();

//    bookquery.prepare(sql);
//    bookquery.bindValue(":id", "A3484962");
//    bookquery.bindValue(":name", "《通信与电子信息科技英语》");
//    bookquery.bindValue(":image","./books/A3484962.png");
//    bookquery.exec();

    bookmodel = new QSqlQueryModel();
    bookmodel->setQuery("select * from book",bookdb);//这里必须加第二个参数，否则不会显示表格数据，但是会有数据内容生成
    bookmodel->setHeaderData(0, Qt::Horizontal, "编号");
    bookmodel->setHeaderData(1, Qt::Horizontal, "书名");
    bookmodel->setHeaderData(2, Qt::Horizontal, "图片");

}
